package cn.lil.servlet;

import cn.lil.model.Bearing;
import cn.lil.model.Order;
import cn.lil.model.OrderItem;
import cn.lil.model.User;
import cn.lil.service.BearingService;
import cn.lil.service.OrderService;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet(name = "OrderItemAddServlet", value = "/OrderItemAddServlet")
public class OrderItemAddServlet extends HttpServlet {
    OrderService orderService = new OrderService();
    BearingService bearingService = new BearingService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        OrderItem orderItem = null;
        System.out.println((request.getSession().getAttribute("order")) + "  :order的值");
        Order o = (Order) request.getSession().getAttribute("order");
        User u = (User) request.getSession().getAttribute("user");
        int orderId = o.getId();
        int bearingId = ((Bearing) request.getSession().getAttribute("bearing")).getId();
        Bearing b = null;
        try {
            b = bearingService.selectBearingById(bearingId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        int amount = 1;
        orderItem = new OrderItem(0, b.getPrice(), amount, bearingId, orderId);
//        获取当前order对象的itemList
        List<OrderItem> orderItemList = o.getItemList();
        try {
            orderService.insertOrderItem(orderItem);
//            如果添加成功则将当前item放入当前用户order的itemList中
            orderItemList.add(orderItem);
            o.addBearing(b);
//            重新在数据库中获取当前用户的order的新的item列表数据
            orderItemList = orderService.selectAllitem(o.getId());
            int a = 0;
            float tf = 0f;
            for (OrderItem oi : orderItemList) {
                a += oi.getAmount();
                tf += oi.getPrice();
            }
            orderService.updateOrderAmountAndtotal(o.getId(), u.getId(), a, tf);
        } catch (SQLException e) {
            e.printStackTrace();
        }
//        更新会话中的数据
        System.out.println(o.getItemList());
        o.setItemList(orderItemList);
        request.getSession().setAttribute("order", o);
        request.getRequestDispatcher("/OrderListServlet").forward(request, response);
    }
}
